﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using snat.proxy;
using snat.proxy.items.exceptions;

namespace snat.proxy.items {
    public class Connection : Item, IComparable {

        private Entity from;
        public Entity From {
            get {
                return from;
            }
        }

        private Entity to;
        public Entity To {
            get {
                return to;
            }
        }

        private bool isInitial;
        public bool IsInitial {
            get {
                return isInitial;
            }
        }

        object strengthLock = new object();

        private double? strength = null;
        public double Strength {
            get {
                lock (strengthLock) {
                    if (strength == null) {
                        Instantiate();
                    }
                }
                return (double)strength;
            }
        }
        
        public Connection(DataRow _row, bool _isGreedy = false)
            : this(new Entity(_row, "FromEntityID", "Sender", _isGreedy),
                   new Entity(_row, "ToEntityID", "Recipient", _isGreedy)) {
                       if (_isGreedy) {
                           this.strength = _row.Field<float>("Strength");
                           this.isInitial = _row.Field<bool>("Initial");
                       }
        }

        public Connection(Entity _from, Entity _to, bool _isInitial = false, double? _strength = null) {
            this.from = _from;
            this.to = _to;
            this.isInitial = _isInitial;
            this.strength = _strength;
        }

        public override String ToString() {
            return String.Join(" ", "From: ", From, "To: ", To, "Strength: ", strength, "Initial: ", IsInitial);
        }

        public int CompareTo(object obj) {
            return Strength.CompareTo((obj as Connection).Strength);
        }

        private void Instantiate() {
            try
            {
                DataSet strengthSet = DataProxy.Instance.RunQuery(
                    @"SELECT Strength FROM Connected
                                WHERE FromEntityID = " + From.ID + " AND ToEntityID = " + To.ID);
                strength = strengthSet.Tables["Table"].Rows[0].Field<float>("Strength");
            }
            catch (IndexOutOfRangeException)
            {
             
                throw new NoResultFromSQLException(@"SELECT * FROM Connected
                                WHERE FromEntityID = " + From.ID + " AND ToEntityID = " + To.ID);
            }
        }
    }
}
